const { validationResult, body, param, query } = require('express-validator');

/**
 * 验证结果处理中间件
 * 检查请求参数验证结果，如有错误则返回400响应
 */
const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      code: 400,
      success: false,
      message: '请求参数验证失败',
      details: errors.array().map(err => ({
        field: err.param,
        message: err.msg,
        value: err.value
      }))
    });
  }
  next();
};

/**
 * 教学设计生成接口参数验证
 */
const designGenerateValidator = [
  body('teachingGoal').notEmpty().withMessage('教学目标不能为空'),
  body('duration').isInt({ min: 1 }).withMessage('授课时长必须是大于0的整数'),
  body('style').optional().isString().withMessage('授课风格必须是字符串'),
  validate
];

/**
 * 图像生成接口参数验证
 */
const imageGenerateValidator = [
  body('knowledgeDesc').notEmpty().withMessage('知识点描述不能为空'),
  body('style').optional().isString().withMessage('图像风格必须是字符串'),
  validate
];

/**
 * 视频生成接口参数验证
 */
const videoGenerateValidator = [
  body('script').notEmpty().withMessage('讲解脚本不能为空'),
  body('duration').isInt({ min: 1 }).withMessage('视频时长必须是大于0的整数'),
  body('animationStyle').optional().isString().withMessage('动画风格必须是字符串'),
  validate
];

/**
 * 练习题生成接口参数验证
 */
const exerciseGenerateValidator = [
  body('knowledgePointIds').isArray({ min: 1 }).withMessage('知识点ID列表不能为空且必须是数组'),
  body('questionTypes').isArray({ min: 1 }).withMessage('题型数组不能为空且必须是数组'),
  body('difficultyRatio').optional().isObject().withMessage('难度比例必须是对象'),
  validate
];

/**
 * 试卷生成接口参数验证
 */
const paperGenerateValidator = [
  body('knowledgeRange').isArray({ min: 1 }).withMessage('知识点ID列表不能为空且必须是数组'),
  body('difficultyDistribution').isObject().withMessage('难度分布必须是对象'),
  body('questionTypeRatio').isObject().withMessage('题型比例必须是对象'),
  validate
];

/**
 * 个性化定制接口参数验证
 */
const customGenerateValidator = [
  body('courseOutlineId').isInt({ min: 1 }).withMessage('课程大纲ID必须是大于0的整数'),
  body('weakKnowledgeIds').optional().isArray().withMessage('薄弱知识点ID列表必须是数组'),
  validate
];

/**
 * 反馈提交接口参数验证
 */
const feedbackSubmitValidator = [
  body('resourceId').isInt({ min: 1 }).withMessage('资源ID必须是大于0的整数'),
  body('evaluation').isIn(['satisfied', 'unsatisfied']).withMessage('评价必须是满意或不满意'),
  body('suggestion').optional().isString().withMessage('建议必须是字符串'),
  validate
];

/**
 * 资源保存接口参数验证
 */
const resourceSaveValidator = [
  body('resourceId').isInt({ min: 1 }).withMessage('资源ID必须是大于0的整数'),
  validate
];

/**
 * 资源导出接口参数验证
 */
const resourceExportValidator = [
  param('resourceId').isInt({ min: 1 }).withMessage('资源ID必须是大于0的整数'),
  validate
];

module.exports = {
  designGenerateValidator,
  imageGenerateValidator,
  videoGenerateValidator,
  exerciseGenerateValidator,
  paperGenerateValidator,
  customGenerateValidator,
  feedbackSubmitValidator,
  resourceSaveValidator,
  resourceExportValidator
};